package com.cpip.cart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cpip.cart.mapper.BuyerMapper;
import com.cpip.cart.mapper.CartMapper;
import com.cpip.cart.mapper.GoodsMapper;
import com.cpip.cart.mapper.ManufacturerMapper;
import com.cpip.cart.service.CartService;
import com.cpip.common.pojo.Buyer;
import com.cpip.common.pojo.Cart;
import com.cpip.common.pojo.Goods;
import com.cpip.common.pojo.Manufacturer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartSreviceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private BuyerMapper buyerMapper;
    @Autowired
    private ManufacturerMapper manufacturerMapper;

    @Override
    public List<Cart> selectCart(int buyerId) {
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("buyer_id", buyerId);
        return cartMapper.selectList(wrapper);
    }

    @Override
    public void add(Cart cart) {
        Goods goods = goodsMapper.selectById(cart.getGoodsId());
        cart.setGoodsId(cart.getGoodsId());
        cart.setGoodsName(goods.getGoodsName());
        cart.setGoodsPrice(goods.getPrice());
        cart.setTotalPrice(cart.getGoodsPrice() * cart.getGoodsNum());
        cart.setStatus("待付款");
        cart.setManufacturerId(goods.getManufacturerId());
        cart.setManufacturerName(goods.getManufacturerName());
        //厂家信息设置
        Manufacturer manufacturer = manufacturerMapper.selectById(goods.getManufacturerId());
        cart.setManufacturerAddress(manufacturer.getManufacturerAddress());
        cart.setManufacturerContact(manufacturer.getContact());
        //采购员信息设置
        Buyer buyer = buyerMapper.selectById(cart.getBuyerId());
        cart.setBuyerName(buyer.getBuyerName());
        cart.setBuyerAddress(buyer.getBuyerAddress());
        cart.setBuyerContact(buyer.getContact());
        //插入
        cartMapper.insert(cart);
    }

    @Override
    public void update(Long cartId, String status) {
        Cart cart = cartMapper.selectById(cartId);
        cart.setStatus(status);
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", cartId);
        cartMapper.update(cart, wrapper);
    }

    @Override
    public int delete(int cartId) {
        return cartMapper.deleteById(cartId);
    }

    @Override
    public int selectNumber(int buyerId, int goodsId, int manufacturerId) {
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("buyer_id", buyerId).eq("goods_id", goodsId).eq("manufacturer_id", manufacturerId);
        Cart cart = cartMapper.selectOne(wrapper);
        return cart.getGoodsNum();
    }
}
